﻿package com.ccx.coachsite.util.net;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import com.ccx.coachsite.data.SystemConst;

/**
 * URL解析器</br> 1.为URL提供曾删改参数的方法。</br>2.为URL提供添加域的方法。</br>
 */
public class UrlParse {
	private Map<String, String> mMap = new HashMap<String, String>();
	private StringBuilder mHeaderBuilder;

	public UrlParse(String url) {
		iniUrl(url);
	}
	
	public UrlParse(){
		
	}

	/**
	 * 初始化URL
	 * 
	 * @param url
	 */
	public void iniUrl(String url) {
		this.mMap.clear();
		// 设置通用参数
		UrlManager.setCommonUrlParam(this);
		int pos = url.indexOf("?");
		if (pos == -1) {
			this.mHeaderBuilder = new StringBuilder(url);
			return;
		}
		this.mHeaderBuilder = new StringBuilder(url.substring(0, pos));
		String temp = url.substring(pos + 1);
		StringTokenizer token = new StringTokenizer(temp, "&", false);
		while (token.hasMoreElements()) {
			String[] str = token.nextToken().split("=");
			if (str.length == 2) {
				this.putValue(str[0], str[1]);
			}
		}
	}

	private String decodeUtf8(String str) {
		try {
			if(str==null || "".equals(str)){
				return str;
			}			
			return URLDecoder.decode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 获取对应的UTF8值。
	 * @param key
	 * @return
	 */
	public String getUtf8Value(String key){
		String temp = this.mMap.get(key.toLowerCase());
		return decodeUtf8(temp);
	}

	/**
	 * 获取对应的值。
	 * 
	 * @param key
	 * @return
	 */
	public String getValue(String key) {
		return this.mMap.get(key.toLowerCase());
	}

	/**
	 * 设置对应的值,如果其中有一个为空，不设置。</br> 当参数存在的时候，会代替已存在的参数。
	 */
	public UrlParse putValue(String key, String value) {
		if (key == null || value == null)
			return this;
		this.mMap.put(key.toLowerCase(), value);
		return this;
	}

	/**
	 * 移除值
	 * 
	 * @param key
	 */
	public void removeValue(String key) {
		this.mMap.remove(key.toLowerCase());
	}

	/**
	 * 获取解析后的URL地址
	 * the method is old instead of toString method.
	 * @return URL
	 */
	public String getUrl() {
		StringBuilder sb = new StringBuilder(this.mHeaderBuilder);
		sb.append("?");
		sb.append(getUrlParam());
		return sb.toString();
	}
	/**
	 * 获取解析后的URL参数
	 * @return URL
	 */
	public String getUrlParam() {
		StringBuilder sb = new StringBuilder();
		Iterator<String> iterator = this.mMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			sb.append(key);
			sb.append("=");
			sb.append(this.mMap.get(key));
			sb.append("&");
		}
		if (sb.length() > 0) {
			return sb.substring(0, sb.length() - 1);
		}
		return sb.toString();
	}
	/**
	 * 向URL加上域，这里并不考虑特殊情况</br>例如：http://www.google.com/a.aspx
	 * appendRegion("http://www.google.com/a.aspx","hell.aspx");
	 * 所得到的是：http://www.google.com/a.aspx/hell.aspx.
	 * 
	 * @param region
	 * @return
	 */
	public UrlParse appendRegion(String region) {
		String str = this.mHeaderBuilder.toString();
		if (str.endsWith("/")) {
			this.mHeaderBuilder.append(region);
		} else {
			this.mHeaderBuilder.append("/").append(region);
		}
		return this;
	}

	@Override
	public String toString() {
		return getUrl();
	}
	
	public static void setCommonUrlParam(UrlParse parse) {
		parse.putValue("sv", SystemConst.versionName);
		parse.putValue("osv", SystemConst.firmwareVersion);
		parse.putValue("cpu", SystemConst.abi);
		parse.putValue("imei", SystemConst.imei);
		parse.putValue("imsi", SystemConst.imsi);
		parse.putValue("dm", URLEncoder.encode(SystemConst.model));
		
	}
	
}
